﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;

namespace Dting
{
    #region  //ini类
    public class ini_Class
    {
        public string _iniPath;  //ini连接路径

        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
            string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);


        //构造函数文件路径初始
        public ini_Class(string iniPath)
        {
            _iniPath = Path.GetFullPath(Application.StartupPath + "\\" + iniPath);
            //_iniPath = Path.GetFullPath(iniPath);
        }

        /// <读INI文件>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="NoText"></param>
        /// <文件路径="iniFilePath"></param>
        /// <returns></returns>
        public string Read_Ini(string Section, string Key, string sfc)
        {
            //解析字符
            try
            {
                Key = Key.Replace("\"", "");
                Key = Key.Replace(sfc, "");
            }
            catch (Exception e) {; }

            try
            {
                if (File.Exists(_iniPath))
                {
                    StringBuilder temp = new StringBuilder(1024);
                    GetPrivateProfileString(Section, Key, "", temp, 1024, _iniPath);
                    return temp.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
            catch (Exception e) { return String.Empty; }

        }
        public string Read_Ini(string Section, string Key)
        {
            //解析字符
            try
            {
                Key = Key.Replace("\"", "");
            }
            catch (Exception e) {; }

            try
            {
                if (File.Exists(_iniPath))
                {
                    StringBuilder temp = new StringBuilder(1024);
                    GetPrivateProfileString(Section, Key, "", temp, 1024, _iniPath);
                    return temp.ToString();
                }
                else
                {
                    return String.Empty;
                }
            }
            catch (Exception e) { return String.Empty; }

        }
        /// <写Ini文件>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        /// <param name="iniFilePath"></param>
        /// <returns></returns>
        public int Write_Ini(string Section, string Key, string Value)
        {
            try
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, _iniPath);
                if (OpStation == 0)
                { return 0; }
                else
                { return 1; }
            }
            catch (Exception e) { return 1; }
        }

    }
    #endregion

    #region //二进制序列化
    public class Serialize_Class  //序列化的位置务必加上[Serializable]
    {
        public int  Serialize<T>(T source,string file_path)//序列化方法  
        {
            if (!typeof(T).IsSerializable)
            {
                //MessageBox.Show("类型必须是可序列化", "提示");
                return 1;
            }

            if (Object.ReferenceEquals(source, null))
            {
                //MessageBox.Show("实例不是相同的实例", "提示");
                return 2;
            }
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Create))//创建一个文件流，对文件进行写入
                {
                    BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                    bf.Serialize(fs, source); //序列化到硬盘
                    fs.Close();//关闭文件流
                }
                return 0;
            }
            catch
            {
                return 3;
            }
        }
        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// DataTable表数据显示到DataGridview 必须要有列名并与DataTable对齐
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="dataGridView">DataGridView</param>
        /// <returns>true成功；false失败</returns>
        public int GridviewShowDataTable(DataTable table, DataGridView dataGridView)
        {
            try
            {
                if (table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        dataGridView.Rows.Add();
                        for (int j = 0; j < (table.Columns.Count - 0); j++)
                        {
                            dataGridView.Rows[i].Cells[j + 0].Value = table.Rows[i].ItemArray[j + 0].ToString();
                            //Application.DoEvents();//可以交出控制权但是慢
                        }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            { return 1; }

        }

        /// <summary>
        /// DataGridView导出为Datatable
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <returns>Datatable</returns>
        public DataTable GetDataGridView(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

    }

    #endregion

    #region //生成条码与二维码
    public class User_barcode
    {
        /// <summary>
        /// 生成条码与二维码
        /// </summary>
        /// <param name="barcode_info">条码信息</param>
        /// <param name="barcode_byte">条码类型</param>
        /// <param name="Height">条码高度</param>
        /// <param name="Width">条码宽度</param>
        /// <returns></returns>
        public Bitmap Create_Barcode(string barcode_info, BarcodeFormat barcode_byte = BarcodeFormat.QR_CODE, int Width = 200, int Height = 200)
        {
            try
            {
                if (barcode_info == string.Empty) return null;

                // 1.设置QR二维码的规格
                ZXing.QrCode.QrCodeEncodingOptions qrEncodeOption = new ZXing.QrCode.QrCodeEncodingOptions();
                qrEncodeOption.CharacterSet = "UTF-8"; // 设置编码格式，否则读取'中文'乱码
                qrEncodeOption.Height = Height;
                qrEncodeOption.Width = Width;
                qrEncodeOption.Margin = 0; // 设置周围空白边距
                qrEncodeOption.NoPadding = false;
                qrEncodeOption.ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.M;
                qrEncodeOption.PureBarcode = false;//紧输出条码


                // 2.生成条形码图片并保存
                BarcodeWriter wr = new BarcodeWriter();
                wr.Format = barcode_byte; // 二维码
                wr.Options = qrEncodeOption;
                return wr.Write(barcode_info);
            }
            catch (Exception er)
            {
                return null;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="buf_Image"></param>
        /// <param name="str"></param>
        /// <param name="width"></param>
        /// <param name="Height"></param>
        /// <returns></returns>  Color.FromArgb(151, 156, 158)
        public Image GetContorlImage(Image buf_Image, string str, int width, int Height)
        {
            var bmp = new Bitmap(width, Height);
            bmp.SetResolution(300,300);
            using (var g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                g.Clear(Color.Transparent);

                using (var p = new Pen(Color.FromArgb(151, 156, 158), 2f))
                {
                    g.FillRectangle(Brushes.White, new Rectangle(0, 0, width, Height));
                    g.DrawImage(buf_Image, (width - buf_Image.Width) / 2, (Height - buf_Image.Height) / 2);

                    //设置打印内容及其字体，颜色和位置
                    //g.DrawString(str, new Font(new FontFamily("黑体"), 24), System.Drawing.Brushes.Black, 50, 50); 

                }
            }
            return bmp;
        }

    }

    #endregion

    #region//打印
    public class User_Print
    {
        public Image buf_data = null;
        public bool PrintToFile = true;
        public bool Preview_state = true;

        //条码位置
        public int info_x = 5;
        public int info_y = 5;

        //实例化打印对象  preview
        PrintDocument printDocument1 = new PrintDocument();


        public void Printer(int DpiX, int DpiY,int _Copies,  string Dbvice = "Microsoft Print to PDF")
        {
            //指定打印机
            printDocument1.PrinterSettings.PrinterName = Dbvice;
            //设置页边距
            printDocument1.PrinterSettings.DefaultPageSettings.Margins.Left = 0;
            printDocument1.PrinterSettings.DefaultPageSettings.Margins.Top = 0;
            printDocument1.PrinterSettings.DefaultPageSettings.Margins.Right = 0;
            printDocument1.PrinterSettings.DefaultPageSettings.Margins.Bottom = 0;

            printDocument1.PrinterSettings.Copies = (short)_Copies;

            //设置尺寸大小，如不设置默认是A4纸
            //A4纸的尺寸是210mm×297mm，
            //当你设定的分辨率是72像素/英寸时，A4纸的尺寸的图像的像素是595×842
            //当你设定的分辨率是150像素/英寸时，A4纸的尺寸的图像的像素是1240×1754
            //当你设定的分辨率是300像素/英寸时，A4纸的尺寸的图像的像素是2479×3508，
            //printDocument1.DefaultPageSettings.PaperSize = new PaperSize("A4", 595, 842);

            //设置打印用的纸张,当设置为Custom的时候，可以自定义纸张的大小
            //printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", (int)MillimetersToInches(30) * 100, (int)MillimetersToInches(15) * 100);
            printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", DpiX, DpiY);

            //是否打印到文件开启或关闭
            printDocument1.PrinterSettings.PrintToFile = false;
            printDocument1.PrinterSettings.PrintFileName = Application.StartupPath + @"\Print_test\barcode_test.pdf";

            //注册PrintPage事件，打印每一页时会触发该事件
            printDocument1.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);


            DialogResult result = DialogResult.Cancel;
            if (!Preview_state)
            {
                //初始化打印预览对话框对象
                PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
                //将printDocument1对象赋值给打印预览对话框的Document属性
                printPreviewDialog1.Document = printDocument1;

                //打开打印预览对话框
                result = printPreviewDialog1.ShowDialog();
            }
            try
            {
                if (!Preview_state)
                {
                    if (result == DialogResult.OK)
                        printDocument1.Print();//开始打印
                }
                else
                {
                    printDocument1.Print();//开始打印
                }
            }
            catch (InvalidPrinterException er)
            {
                ;
            }
            finally
            {
                printDocument1.Dispose();
            }

        }

        private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;

            //设置打印内容及其字体，颜色和位置
            //e.Graphics.DrawString("Hello World！", new Font(new FontFamily("黑体"), 24), System.Drawing.Brushes.Red, 50, 50);

            if (buf_data != null)
            {
                e.Graphics.DrawImage(buf_data, new Rectangle((int)e.Graphics.DpiX / 2 - (B_width / 2) + info_x, info_y, B_width, B_height), new Rectangle(0, 0, buf_data.Width, buf_data.Height), GraphicsUnit.Pixel);
                //buf_data.Dispose();
            }

        }

        //
        public string[] GetPrinterDevice()
        {
            try
            {
                List<string> PrintS = new List<string>();
                foreach (string sPrint in PrinterSettings.InstalledPrinters)//获取所有打印机名称
                {
                    PrintS.Add(sPrint);
                }
                return PrintS.ToArray();
            }
            catch { return null; }
        }


        int B_width = 0;
        int B_height = 0;

        /// <summary>
        /// 生成条码与二维码
        /// </summary>
        /// <param name="barcode_info">条码信息</param>
        /// <param name="Height">条码高度</param>
        /// <param name="Width">条码宽度</param>
        /// <param name="DpiX">条码高度</param>
        /// <param name="DpiY">条码宽度</param>
        /// <param name="barcode_byte">条码类型</param>
        /// <returns></returns>
        public Bitmap Create_Barcode(string barcode_info, int Width, int Height, int DpiX, int DpiY, BarcodeFormat barcode_byte = BarcodeFormat.QR_CODE)
        {
            try
            {

                B_width = (int)(MillimetersToInches(Width) * 100);
                B_height = (int)(MillimetersToInches(Height) * 100);

                int dpix = DpiX;
                int dpiy = DpiY;


                int _Width = (int)(B_width * dpix / 100.0f);
                int _Height = (int)(B_height * dpiy / 100.0f);

                if (barcode_info == string.Empty) return null;

                // 1.设置QR二维码的规格
                ZXing.QrCode.QrCodeEncodingOptions qrEncodeOption = new ZXing.QrCode.QrCodeEncodingOptions();
                qrEncodeOption.CharacterSet = "UTF-8"; // 设置编码格式，否则读取'中文'乱码
                qrEncodeOption.Height = _Height;
                qrEncodeOption.Width = _Width;
                qrEncodeOption.Margin = 0; // 设置周围空白边距
                qrEncodeOption.NoPadding = false;
                qrEncodeOption.ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.M;
                qrEncodeOption.PureBarcode = true;//紧输出条码

                // 2.生成条形码图片并保存
                BarcodeWriter wr = new BarcodeWriter();
                wr.Format = barcode_byte; // 二维码
                wr.Options = qrEncodeOption;
                return wr.Write(barcode_info);
            }
            catch (Exception er)
            {
                return null;
            }
        }


        //二维码背景填充
        public Image GetContorlImage(Image buf_Image, string str, float str_Size = 20)
        {
            int width = buf_Image.Width;
            int Height = buf_Image.Height;
            Font font = new Font(new FontFamily("黑体"), str_Size);
            Size textSize = TextRenderer.MeasureText(str, font);
            var bmp = new Bitmap(width, Height + textSize.Height, PixelFormat.Format32bppArgb);
            using (var g = Graphics.FromImage(bmp))
            {
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                g.PixelOffsetMode = PixelOffsetMode.Half;
                g.Clear(Color.Transparent);

                using (var p = new Pen(Color.FromArgb(151, 156, 158), 2f))
                {
                    g.DrawImage(buf_Image, 0, 0);
                    g.FillRectangle(Brushes.White, new Rectangle(0, Height, width, (int)textSize.Height));

                    ;
                    //设置打印内容及其字体，颜色和位置
                    g.DrawString(str, font, Brushes.Black, (width - textSize.Width) / 2, Height);

                }
            }
            return bmp;
        }

        public static float MillimetersToInches(float mm)
        {
            return (float)Math.Round(mm / 25.4f, 2);
        }

    }
    #endregion

}

